package com.ques.interceptors;

import com.ques.annotations.LoginRequired;
import com.ques.utils.RedisUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;
import org.springframework.util.StringUtils;
import org.springframework.web.method.HandlerMethod;
import org.springframework.web.servlet.handler.HandlerInterceptorAdapter;
import redis.clients.jedis.Jedis;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * @author zq  2020-02-08
 */
@Component
public class AuthInterceptor extends HandlerInterceptorAdapter  {

    @Value("${spring.signKey:signKey}")
    private String signKey;


    @Autowired
    RedisUtil redisUtil ;


    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        System.out.println("拦截------------------------");
        // 拦截代码
        // 判断被拦截的请求的访问的方法的注解(是否时需要拦截的)
        HandlerMethod hm = null ;
        if (handler instanceof  HandlerMethod){

            hm  = (HandlerMethod) handler;
        }else{
            return true ;
        }


        LoginRequired loginRequiredAnnotation = hm.getMethodAnnotation(LoginRequired.class);
        // 是否拦截
        if (loginRequiredAnnotation == null) {
            return true;
        }
        boolean required = loginRequiredAnnotation.loginSuccess();
//        可以放浏览器
//        也可以通过header传输

        if ( required) {

            String token = request.getHeader("token");
            String id = request.getHeader("id");

            if (StringUtils.isEmpty(token) || StringUtils.isEmpty(id)) {
                // 信息不全
                return false;
            } else {
//                验证token
//                从缓存中获取token
                Jedis jedis = redisUtil.getJedis();
                String tokenDb = jedis.get("user:" + id + ":token");
                jedis.close();
                if (StringUtils.isEmpty(tokenDb) || !tokenDb.equals(token)){
                    System.out.println("验证成功");
                    return true;
                } else {
                    System.out.println("验证失败");
                    return false;
                }
            }
        }
        return true;
    }
}
